#include "mysql_message.h"

#include <sstream>

#include "log.h"
#include "message-odb.hxx"

namespace chat {
bool MessageTable::insert(Message& message) {
    try {
        // 获取事务对象开启事务
        odb::transaction trans(db_->begin());

        db_->persist(message);

        // 提交事务
        trans.commit();

    } catch (const std::exception& e) {
        LOG_ERROR("新增message[{}]失败: {}", message.message_id(), e.what());

        return false;
    }

    return true;
}

bool MessageTable::remove(const std::string& chat_session_id) {
    try {
        // 获取事务对象开启事务
        odb::transaction trans(db_->begin());

        db_->erase_query<Message>(odb::query<Message>::chat_session_id ==
                                  chat_session_id);

        // 提交事务
        trans.commit();

    } catch (const std::exception& e) {
        LOG_ERROR("删除message[{}]失败: {}", chat_session_id, e.what());

        return false;
    }

    return true;
}

std::vector<Message> MessageTable::recent(const std::string& chat_session_id,
                                          size_t count) {
    std::vector<Message> messages;

    std::stringstream condition;
    condition << "chat_session_id = '" << chat_session_id << "'";
    condition << " order by created_time desc";
    condition << " limit " << count;

    try {
        // 获取事务对象开启事务
        odb::transaction trans(db_->begin());

        auto results = db_->query<Message>(condition.str());
        for (auto& result : results) {
            messages.push_back(result);
        }

        trans.commit();

    } catch (const std::exception& e) {
        LOG_ERROR("获取会话[{}]最近的{}条消息失败: {}", chat_session_id, count,
                  e.what());

        return messages;
    }

    return messages;
}

std::vector<Message> MessageTable::range(const std::string& chat_session_id,
                                         const boost::posix_time::ptime begin,
                                         const boost::posix_time::ptime end) {
    std::vector<Message> messages;

    try {
        // 获取事务对象开启事务
        odb::transaction trans(db_->begin());

        auto results = db_->query<Message>(
            odb::query<Message>::chat_session_id == chat_session_id &&
            odb::query<Message>::created_time >= begin &&
            odb::query<Message>::created_time <= end);

        for (auto& result : results) {
            messages.push_back(result);
        }

        trans.commit();

    } catch (const std::exception& e) {
        LOG_ERROR("获取会话[{}]时间范围[{} - {}]的消息失败: {}",
                  chat_session_id, boost::posix_time::to_simple_string(begin),
                  boost::posix_time::to_simple_string(end), e.what());
    }

    return messages;
}
}  // namespace chat